<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2023/9/20
 * Time: 9:45
 */

namespace app\api\controller;

use think\Db;

class Biggoods extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;

    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }

    /**
     * 家大业大商品分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cateList(){
        $fCate = Db::table('up_big_goods_cate')
            ->where('gc_level', 1)
            ->field('gc_id, gc_name')
            ->order('gc_sort desc')
            ->select();
        if($fCate){
            $sCate = Db::table('up_big_goods_cate')
                ->where('gc_level', 2)
                ->field('gc_id, gc_name, gc_pid')
                ->order('gc_sort desc')
                ->select();
            foreach ($fCate as $k => $v){
                $children = [];
                if($sCate){
                    foreach ($sCate as $kk => $vv){
                        if($vv['gc_pid'] == $v['gc_id']){
                            $children[$kk] = $vv;
                        }
                    }
                }
                $fCate[$k]['children'] = $children;
            }
            return json(['status' => 200, 'msg' => $fCate]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 商品列表
     * keyword      搜索关键字
     * fCate        一级分类ID
     * sCate        二级分类ID
     * page         页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList(){
        $keyword = input('keyword');
        $fCate = input('fCate') ? input('fCate') : 0;
        $sCate = input('sCate') ? input('sCate') : 0;

        $where['goods_status'] = 1;
        if($keyword) $where['goods_name'] = ['LIKE', '%' . $keyword . '%'];
        if($fCate) $where['goods_first_cate'] = $fCate;
        if($sCate) $where['goods_second_cate'] = ['LIKE', '%,' . $sCate . ',%'];

        $goods = $this->selectGoods($where);
        if($goods){
            return json(['status' => 200, 'msg' => $goods]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 商品详情
     * goods_id     商品ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsDetail(){
        $goods_id = input('goods_id');

        $where['goods_id'] = $goods_id;
        $data = $this->findGoods($where);

        if($data['goods_status'] != 1) return json(['status' => 0, 'msg' => '该商品状态异常，请刷新重试']);

        // 图片
        if($data['goods_images']){
            $data['goods_images'] = explode(',', $data['goods_images']);
        }else{
            $data['goods_images'] = [];
        }

        // 购物车数量
        $shopCarNumber = $this->shopCar(2);
        $data['shopCarNumber'] = $shopCarNumber;

        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * 添加购物车
     * goods_id      商品ID
     * goodsNumber   商品数量
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addShopCar(){
        $goods_id = input('goods_id');
        $goodsNumber = input('goodsNumber');

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_big_rule')->find();
        if($user['user_big_rule'] == 2) return json(['status' => 0, 'msg' => '权限不足']);

        $goods = Db::table('up_big_goods')
            ->where('goods_id', $goods_id)
            ->field('goods_stock')
            ->find();
        if($goodsNumber > $goods['goods_stock']) return json(['status' => 0, 'msg' => '库存不足']);

        $haveIn = Db::table('up_big_goods_car')
            ->where(['car_user_id' => $this->user_id, 'car_goods_id' => $goods_id])
            ->find();
        if($haveIn){
            $res = Db::table('up_big_goods_car')->where('car_id', $haveIn['car_id'])->setInc('car_goods_number', $goodsNumber);
        }else{
            $insert = [
                'car_user_id'      => $this->user_id,
                'car_goods_id'     => $goods_id,
                'car_goods_number' => $goodsNumber,
                'car_time'         => $this->create_time
            ];
            $res = Db::table('up_big_goods_car')->insert($insert);
        }
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败，请稍后重试']);
        }
    }

    /**
     * 购物车列表
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopCarList(){
        $data = $this->shopCar(1);
        if($data){
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 增加购物车商品数量
     * car_id     购物车ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function incShopCar(){
        $car_id = input('car_id');

        $car = Db::table('up_big_goods_car')
            ->join('up_big_goods', 'car_goods_id = goods_id', 'LEFT')
            ->field('goods_stock, car_goods_number')
            ->find();
        if($car['car_goods_number'] >= $car['goods_stock']) return json(['status' => 0, 'msg' => '超过最大库存']);

        $res = Db::table('up_big_goods_car')->where('car_id', $car_id)->setInc('car_goods_number');
        if($res){
            return json(['status' => 200, 'msg' => true]);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }

    /**
     * 减少购物车商品数量
     * car_id    购物车ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function decShopCar(){
        $car_id = input('car_id');

        $car = Db::table('up_big_goods_car')->where('car_id', $car_id)->field('car_goods_number')->find();
        if($car['car_goods_number'] <= 1) return json(['status' => 0, 'msg' => '商品数量不能小于1']);

        $res = Db::table('up_big_goods_car')->where('car_id', $car_id)->setDec('car_goods_number');
        if($res){
            return json(['status' => 200, 'msg' => true]);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }

    /**
     * 设置购物车商品数量
     * car_id           购物车ID
     * goodsNumber      购物车商品数量
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setShopCar(){
        $car_id = input('car_id');
        $goodsNumber = input('goodsNumber');

        $car = Db::table('up_big_goods_car')
            ->join('up_big_goods', 'car_goods_id = goods_id', 'LEFT')
            ->field('goods_stock, car_goods_number')
            ->find();
        if($goodsNumber > $car['goods_stock']) return json(['status' => 0, 'msg' => '库存不足']);

        if($goodsNumber == $car['car_goods_number']){
            return json(['status' => 200, 'msg' => true]);
        }else{
            $res = Db::table('up_big_goods_car')->where('car_id', $car_id)->setField('car_goods_number', $goodsNumber);
            if($res){
                return json(['status' => 200, 'msg' => true]);
            }else{
                return json(['status' => 0, 'msg' => '操作失败，请稍后重试']);
            }
        }
    }

    /**
     * 删除购物车
     * car_ids    购物车IDS，逗号拼接
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delShopCar(){
        $car_ids = input('car_ids');
        $res = Db::table('up_big_goods_car')->where('car_id', 'IN', $car_ids)->delete();
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }

    /**
     * 校验库存
     * goods_id       商品ID
     * goodsNumber    商品数量
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkStock(){
        $goods_id = input('goods_id');
        $goodsNumber = input('goodsNumber');

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_big_rule')->find();
        if($user['user_big_rule'] == 2) return json(['status' => 0, 'msg' => '权限不足']);

        $goods = Db::table('up_big_goods')
            ->where('goods_id', $goods_id)
            ->field('goods_stock')
            ->find();
        if($goodsNumber > $goods['goods_stock']) return json(['status' => 0, 'msg' => '库存不足']);
        return json(['status' => 200, 'msg' => true]);
    }

    /**
     * 提交订单页面
     * goods_id        商品ID
     * goods_number    商品数量
     * car_ids         购物车IDS，逗号隔开
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showOrderPage(){
        $goods_id = input('goods_id');
        $goods_number = input('goods_number');
        $car_ids = input('car_ids');

        $_goods_number = 0;
        $_goods_total_price = 0;
        // 商品
        if($goods_id){
            $where['goods_id'] = $goods_id;
            $goods = $this->findGoods($where);
            $_goods_number = $goods_number;
            $_goods_total_price = $goods_number * $goods['goods_vip_price'];
        }else{
            if(!$car_ids) return json(['status' => 0, 'msg' => '请选择需要结算的商品']);
            $goods = Db::table('up_big_goods_car')
                ->join('up_big_goods', 'goods_id = car_goods_id', 'LEFT')
                ->where('car_id', 'IN', $car_ids)
                ->field('goods_id, goods_name, goods_price, goods_vip_price, goods_spec, car_goods_number, 
                goods_thumb')
                ->order('car_time desc')
                ->select();

            if($goods){
                foreach ($goods as $k => $v){
                    $_goods_number += $v['car_goods_number'];
                    $_goods_total_price += $v['car_goods_number'] * $v['goods_vip_price'];
                }
            }
        }

        // 快递
        $express = Db::table('up_about')->where('id', 7)->value('content');

        // 可用积分
        $user_balance = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_big_balance');
        return json([
            'status' => 200,
            'msg' => $goods,
            'express' => $express,
            'balance' => $user_balance,
            '_goods_number' => $_goods_number,
            '_goods_total_price' => $_goods_total_price
        ]);
    }

    /**
     * 提交订单---立即购买
     * goods_id       商品ID
     * goodsNumber    商品数量
     * addr_id        收货地址ID
     * order_remark   订单备注
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function commitOneOrder(){
        $goods_id = input('goods_id');
        $goodsNumber = input('goodsNumber') ? input('goodsNumber') : 0;
        $addr_id = input('addr_id');
        $order_remark = input('order_remark');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);
        if(!$goods_id) return json(['status' => 0, 'msg' => '请选择正确的商品']);
        if($goodsNumber == 0) return json(['status' => 0, 'msg' => '商品数量不能为0']);
        if(!$addr_id) return json(['status' => 0, 'msg' => '请选择收货地址']);

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_big_balance, user_big_rule')->find();
        if($user['user_big_rule'] == 2) return json(['status' => 0, 'msg' => '暂无购买权限']);

        $goods = Db::table('up_big_goods')
            ->where('goods_id', $goods_id)
            ->field('goods_status, goods_vip_price, goods_stock')
            ->find();
        if($goods['goods_status'] != 1) return json(['status' => 0, 'msg' => '该商品状态异常，请刷新列表重试']);
        if($goods['goods_stock'] <= $goodsNumber) return json(['status' => 0, 'msg' => '库存不足']);

        $totalPrice = $goodsNumber * $goods['goods_vip_price']; // 总价
        if($totalPrice > $user['user_big_balance']) return json(['status' => 222, 'msg' => '可用积分不足']);

        $order_num = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);

        $order = [
            'bo_user_id' => $this->user_id,
            'bo_number'  => $order_num,
            'bo_total_price' => $totalPrice,
            'bo_total_number' => $goodsNumber,
            'bo_remark' => $order_remark,
            'bo_create_time' => $this->create_time
        ];

        $field = 'addr_id, addr_user_name, addr_user_phone, addr_sheng, addr_shi, addr_qu, addr_address';

        $order_addr = Db::table('up_user_address')
            ->where('addr_id', $addr_id)
            ->field($field)
            ->find();
        $order['bo_addr_id'] = $order_addr['addr_id'];
        $order['bo_sheng'] = $order_addr['addr_sheng'];
        $order['bo_shi'] = $order_addr['addr_shi'];
        $order['bo_qu'] = $order_addr['addr_qu'];
        $order['bo_address'] = $order_addr['addr_address'];
        $order['bo_receive_username'] = $order_addr['addr_user_name'];
        $order['bo_receive_phone'] = $order_addr['addr_user_phone'];

        $order_info = [
            'boi_goods_id' => $goods_id,
            'boi_user_id' => $this->user_id,
            'boi_goods_number' => $goodsNumber,
            'boi_goods_price' => $totalPrice
        ];

        Db::startTrans();
        try{
            // 订单表
            $order_id = Db::table('up_big_order')->insertGetId($order);

            // 订单明细表
            $order_info['boi_order_id'] = $order_id;
            Db::table('up_big_order_info')->insert($order_info);

            // 减库存
            Db::table('up_big_goods')
                ->where('goods_id', $goods_id)
                ->inc('goods_sale_num', $goodsNumber)
                ->dec('goods_stock', $goodsNumber)
                ->update();

            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功', 'order_id' => $order_id]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 提交订单---购物车
     * car_ids        购物车IDS
     * addr_id        收货地址
     * order_remark   订单备注
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function commitShopCarOrder(){
        $car_ids = input('car_ids');
        $addr_id = input('addr_id');
        $order_remark = input('order_remark');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);
        if(!$car_ids) return json(['status' => 0, 'msg' => '请选择需要提交的数据']);
        if(!$addr_id) return json(['status' => 0, 'msg' => '请选择收货地址']);

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_big_balance, user_big_rule')->find();
        if($user['user_big_rule'] == 2) return json(['status' => 0, 'msg' => '暂无购买权限']);

        $goods = Db::table('up_big_goods_car')
            ->join('up_big_goods', 'goods_id = car_goods_id', 'LEFT')
            ->field('goods_id, goods_status, goods_name, goods_vip_price, goods_stock, car_goods_number')
            ->where('car_id', 'IN', $car_ids)
            ->select();
        if(!$goods) return json(['status' => 0, 'msg' => '请选择正确的商品']);

        $totalPrice = 0; // 商品总价
        $totalNumber = 0; // 订单商品总数
        $flag = ['flag' => 1, 'msg' => '']; // 用于判断订单异常
        $order_info = []; // 订单详情数组

        foreach ($goods as $k => $v){
            if($v['car_goods_number'] < 1){
                $flag['flag'] = 2;
                $flag['msg'] = '商品' . $v['goods_name'] . '购买数量不可小于1';
                break;
            }

            if($v['goods_stock'] < $v['car_goods_number']){
                $flag['flag'] = 2;
                $flag['msg'] = '商品' . $v['goods_name'] . '库存不足';
                break;
            }

            if($v['goods_status'] != 1){
                $flag['flag'] = 2;
                $flag['msg'] = '商品' . $v['goods_name'] . '状态异常，请重新选择商品';
                break;
            }
            $goodsPrice = $v['goods_vip_price'] * $v['car_goods_number'];
            $totalPrice += $goodsPrice;
            $totalNumber += $v['car_goods_number'];

            $order_info[$k] = [
                'boi_goods_id' => $v['goods_id'],
                'boi_user_id' => $this->user_id,
                'boi_goods_number' => $v['car_goods_number'],
                'boi_goods_price' => $goodsPrice
            ];
        }
        if($flag['flag'] == 2) return json(['status' => 0, 'msg' => $flag['msg']]);

        if($user['user_big_balance'] < $totalPrice) return json(['status' => 222, 'msg' => '可用积分不足']);

        $order_num = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT); // 订单号
        $order = [
            'bo_user_id' => $this->user_id,
            'bo_number' => $order_num,
            'bo_total_price' => $totalPrice,
            'bo_total_number' => $totalNumber,
            'bo_remark' => $order_remark,
            'bo_create_time' => $this->create_time
        ];

        $order_addr = Db::table('up_user_address')
            ->where('addr_id', $addr_id)
            ->field('addr_id, addr_user_name, addr_user_phone, addr_sheng, addr_shi, addr_qu, addr_address')
            ->find();
        $order['bo_addr_id'] = $order_addr['addr_id'];
        $order['bo_sheng'] = $order_addr['addr_sheng'];
        $order['bo_shi'] = $order_addr['addr_shi'];
        $order['bo_qu'] = $order_addr['addr_qu'];
        $order['bo_address'] = $order_addr['addr_address'];
        $order['bo_receive_username'] = $order_addr['addr_user_name'];
        $order['bo_receive_phone'] = $order_addr['addr_user_phone'];

        Db::startTrans();
        try{
            // 订单表
            $order_id = Db::table('up_big_order')->insertGetId($order);

            // 订单明细
            if($order_info){
                foreach($order_info as $kk => $vv){
                    $order_info[$kk]['boi_order_id'] = $order_id;
                }
                Db::table('up_big_order_info')->insertAll($order_info);
            }

            // 减库存&增加销量
            foreach($goods as $kg => $vg){
                Db::table('up_big_goods')
                    ->where('goods_id', $vg['goods_id'])
                    ->inc('goods_sale_num', $vg['car_goods_number'])
                    ->dec('goods_stock', $vg['car_goods_number'])
                    ->update();
            }

            // 删除购物车
            Db::table('up_big_goods_car')->where('car_id', 'IN', $car_ids)->delete();

            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功', 'order_id' => $order_id]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 支付信息展示
     * order_id     订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function nowPayPageShow(){
        $order_id = input('order_id');
        $order = Db::table('up_big_order')
            ->join('up_u_user', 'user_id = bo_user_id', 'LEFT')
            ->where('bo_id', $order_id)
            ->field('user_big_balance, bo_total_price, bo_create_time')
            ->find();
        return json(['status' => 200, 'msg' => $order]);
    }

    /**
     * 订单支付
     * order_id      订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function payOrder(){
        $order_id = input('order_id');

        if(!$order_id) return json(['status' => 0, 'msg' => '请选择需要支付的订单']);

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_big_balance, user_big_rule')->find();
        if($user['user_big_rule'] == 2) return json(['status' => 0, 'msg' => '暂无购买权限']);

        $order = Db::table('up_big_order')
            ->where('bo_id', $order_id)
            ->field('bo_is_pay, bo_total_price')
            ->find();
        if($order['bo_is_pay'] == 2) return json(['status' => 0, 'msg' => '请不要重复支付']);
        if($user['user_big_balance'] < $order['bo_total_price']) return json(['status' => 222, 'msg' => '可用积分不足']);

        $orderInfo = Db::table('up_big_order_info')
            ->join('up_big_goods', 'goods_id = boi_goods_id', 'LEFT')
            ->where('boi_order_id', $order_id)
            ->field('goods_id, boi_goods_number, goods_name, goods_stock, goods_status')
            ->select();

        $flag = ['flag' => 1, 'msg' => '']; // 订单异常
        foreach ($orderInfo as $k => $v){
            if($v['goods_status'] != 1){
                $flag['flag'] = 2;
                $flag['msg'] = '商品' . $v['goods_name'] . '状态异常';
                break;
            }
            if($v['goods_stock'] < $v['boi_goods_number']){
                $flag['flag'] = 2;
                $flag['msg'] = '商品' . $v['goods_name'] . '库存不足';
                break;
            }
        }
        if($flag['flag'] == 2) return json(['status' => 0, 'msg' => $flag['msg']]);

        $orderUpdate = [
            'bo_is_pay' => 2,
            'bo_status' => 2,
            'bo_pay_time' => $this->create_time
        ];

        Db::startTrans();
        try{
            // 修改订单状态
            Db::table('up_big_order')->where('bo_id', $order_id)->update($orderUpdate);

            // 用户可用积分
            Db::table('up_u_user')->where('user_id', $this->user_id)->setDec('user_big_balance', $order['bo_total_price']);

            // 积分明细
            $this->insertBigInte($this->user_id, 2, '购买商品', $order['bo_total_price'], $user['user_big_balance'], 0);

            Db::commit();
            return json([
                'status' => 200,
                'msg' => '支付成功',
                'order_id' => $order_id,
                'order_price' => $order['bo_total_price'],
                'balance' => $user['user_big_balance'] - $order['bo_total_price']
            ]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 订单数量展示
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderNumber(){
        $where = [
            'bo_user_id' => $this->user_id,
            'bo_status' => ['BETWEEN', [1, 3]]
        ];
        $order = $this->orderInfo($where, 1);
        $unPay = 0;
        $unSend = 0;
        $unReceive = 0;
        foreach ($order as $k => $v){
            if($v['bo_status'] == 1){
                $unPay ++;
            }
            if($v['bo_status'] == 2){
                $unSend ++;
            }
            if($v['bo_status'] == 3){
                $unReceive ++;
            }
        }
        return json(['status' => 200, 'msg' => '', 'unPay' => $unPay, 'unSend' => $unSend, 'unReceive' => $unReceive]);
    }

    /**
     * 订单列表
     * status    0 全部   1 待付款   2 待发货   3 待收货   4 已完成
     * page      页码
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderList(){
        $status = input('status'); // 0 全部   1 待付款   2 待发货   3 待收货   4 已完成
        $where['bo_user_id'] = $this->user_id;
        if($status != 0) $where['bo_status'] = $status;

        $order = $this->orderInfo($where, 2);
        if($order){
            $order_ids = array_column($order, 'bo_id');
            $orderInfo = Db::table('up_big_order_info')
                ->join('up_big_goods', 'boi_goods_id = goods_id', 'LEFT')
                ->where('boi_order_id', 'IN', $order_ids)
                ->field('goods_id, goods_name, goods_spec, goods_thumb, goods_vip_price, boi_goods_number, 
                boi_order_id')
                ->select();
            foreach ($order as $k => $v){
                foreach ($orderInfo as $ko => $vo){
                    if($vo['boi_order_id'] == $v['bo_id']){
                        $order[$k]['goods'][] = $vo;
                    }
                }
            }
            return json(['status' => 200, 'msg' => $order]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 订单详情
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function orderDetail(){
        $order_id = input('order_id');
        $detail = Db::table('up_big_order')
            ->join('up_user_address', 'bo_addr_id = addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->where('bo_id', $order_id)
            ->field('bo_id, addr_user_name, addr_user_phone, concat(u1.district, u2.district, u3.district, addr_address) address, 
            bo_total_price, bo_status, bo_remark, bo_number, bo_create_time, bo_pay_time, bo_send_time, 
            bo_over_time, bo_close_time, bo_cancel_time, bo_cancel_reason')
            ->find();
        $goods = Db::table('up_big_order_info')
            ->join('up_big_goods', 'goods_id = boi_goods_id', 'LEFT')
            ->where('boi_order_id', $order_id)
            ->field('goods_name, goods_thumb, goods_spec, goods_vip_price, boi_goods_number, boi_goods_id')
            ->select();
        $detail['goods'] = $goods;
        return json(['status' => 200, 'msg' => $detail]);
    }

    /**
     * 取消订单
     * order_id     订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancelOrder(){
        $order_id = input('order_id');

        if(!$order_id) return json(['status' => 0, 'msg' => '请选择需要取消的订单']);
        $order = Db::table('up_big_order')->where('bo_id', $order_id)->field('bo_status')->find();
        if($order['bo_status'] != 1) return json(['status' => 0, 'msg' => '该订单状态不可取消']);

        $order_info = Db::table('up_big_order_info')
            ->where('boi_order_id', $order_id)
            ->field('boi_goods_id, boi_goods_number')
            ->select();

        $update = [
            'bo_status' => 6,
            'bo_cancel_time' => $this->create_time,
            'bo_cancel_reason' => '用户主动取消'
        ];

        Db::startTrans();
        try{
            // 修改订单状态
            Db::table('up_big_order')->where('bo_id', $order_id)->update($update);

            // 释放库存&减销量
            foreach($order_info as $k => $v){
                Db::table('up_big_goods')
                    ->where('goods_id', $v['boi_goods_id'])
                    ->inc('goods_stock', $v['boi_goods_number'])
                    ->dec('goods_sale_num', $v['boi_goods_number'])
                    ->update();
            }

            Db::commit();
            return json(['status' => 200, 'msg' => '取消成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 确认收货
     * order_id     订单ID
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function overOrder(){
        $order_id = input('order_id');

        if(!$order_id) return json(['status' => 0, 'msg' => '请选择需要取消的订单']);
        $order = Db::table('up_big_order')->where('bo_id', $order_id)->field('bo_status')->find();
        if($order['bo_status'] != 3) return json(['code' => 100, 'msg' => '订单状态异常']);

        // 修改订单状态
        $res = Db::table('up_big_order')
            ->update([
                'bo_id' => $order_id,
                'bo_status' => 4,
                'bo_over_time' => $this->create_time
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }

    /**
     * 订单物流信息
     * @return \think\response\Json
     * order_id      订单ID
     */
    public function showWuLiu(){
        $order_id = input('order_id');
        $order = Db::table('up_big_order')
            ->join('up_user_address', 'addr_id = bo_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('bo_express_company, bo_express_code, bo_addr_id, bo_number, bo_create_time, 
            bo_pay_time, concat(u1.district, u2.district, u3.district, addr_address) address,  
            addr_user_name, addr_user_phone')
            ->where('bo_id', $order_id)
            ->find();

        //*********** 获取快递公司编码
        $code = $order['bo_express_code'];
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $code,
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能判断返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['status' => 0, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';

            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $code . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['status' => 0, 'msg' => $search_data['message'], 'order' => $order/*, 'address' => $address*/]);
                }else{
                    return json(['status' => 200, 'msg' => $search_data['data'], 'order' => $order/*, 'address' => $address*/]);
                }
            }else{
                return json(['status' => 200, 'msg' => [], 'order' => $order/*, 'address' => $address*/]);
            }
        }
    }

    /**
     * 积分明细
     * type    0 全部   1 收入   2 支出
     * page    页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bigInte(){
        $type = input('type'); // 0 全部   1 收入   2 支出

        $where['binte_user_id'] = $this->user_id;
        if($type != 0) $where['binte_type'] = $type;

        $list = Db::table('up_big_integral')
            ->where($where)
            ->field('binte_number, binte_type, binte_desc, binte_price, binte_time')
            ->order('binte_time desc')
            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }



    //*******************************************   公共

    /**
     * @param $dataType
     * dataType     1 列表     2 统计数量
     * @return bool|int|\PDOStatement|string|\think\Collection
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function shopCar($dataType = 1){
        $query = Db::table('up_big_goods_car')
            ->where('car_user_id', $this->user_id);
        if($dataType == 1){
            $data = $query->join('up_big_goods', 'car_goods_id = goods_id', 'LEFT')
                ->field('goods_id, goods_name, goods_thumb, goods_price, goods_vip_price, goods_spec, 
                car_goods_number, car_id, goods_stock')
                ->order('car_time desc')
                ->select();
        }else{
            $data = $query->count();
        }
        return $data;
    }

    /**
     * 查询商品列表
     * @param $where
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function selectGoods($where = []){
        $data = Db::table('up_big_goods')
            ->where($where)
            ->field('goods_id, goods_name, goods_thumb, goods_price, goods_vip_price, goods_spec')
            ->order('goods_sort desc, goods_time desc')
            ->page($this->page, 10)
            ->select();
        return $data;
    }

    /**
     * 商品详情
     * @param $where
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function findGoods($where = []){
        $data = Db::table('up_big_goods')
            ->where($where)
            ->field('goods_id, goods_name, goods_content, goods_images, goods_status, goods_price, 
            goods_vip_price, goods_spec, goods_stock, goods_sale_num, goods_thumb')
            ->find();
        return $data;
    }

    /**
     * 订单信息
     * @param $where
     * @param $type     1 不分页订单列表   2 分页订单列表
     * @return bool|int|\PDOStatement|string|\think\Collection
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function orderInfo($where = [], $type = 1){
        $order = Db::table('up_big_order')->where($where);
        if($type == 1){
            $order->field('bo_status');
        }else{
            $order->field('bo_id, bo_number, bo_total_price, bo_status')
                ->page($this->page, 10)
                ->order('bo_create_time desc');
        }
        $data = $order->select();
        return $data;
    }
}